package com.babylove.project.purchase.service.impl;

import com.babylove.common.exception.CustomException;
import com.babylove.common.utils.DateUtils;
import com.babylove.common.utils.SecurityUtils;
import com.babylove.common.utils.StringUtils;
import com.babylove.common.utils.bean.BeanUtils;
import com.babylove.project.purchase.domain.Contact;
import com.babylove.project.purchase.domain.req.ProviderAddReq;
import com.babylove.project.purchase.domain.resp.TaskEntityResp;
import com.babylove.project.purchase.domain.vo.ProviderVo;
import com.babylove.project.purchase.mapper.PurProviderMapper;
import com.babylove.project.purchase.service.IPurProviderService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @BelongsProject: babylove
 * @BelongsPackage: com.babylove.project.purchase.service.impl
 * @Author: caoqingwen
 * @CreateTime: 2020-06-25 14:40
 * @Description: 供应商管理
 */
@Service
public class PurProviderServiceImpl implements IPurProviderService {

    @Resource
    private PurProviderMapper purProviderMapper;

    @Resource
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    /**
     * 新增、修改供应商
     *
     * @param req
     */
    @Override
    public void saveProvider(ProviderAddReq req) {
        if (req.getId() == null) {
            //校验供应商名称是否唯一
            int count = purProviderMapper.selectCountByProviderNum(req.getProviderName());
            if (count > 0) {
                throw new CustomException("供应商名称重复");
            }

            //新增
            req.setStatus("0");
            req.setPassStatus("0");
            req.setProviderNum(getProviderNum());
            req.setCreateBy(SecurityUtils.getUsername());
            req.setCreateTime(new Date());
            purProviderMapper.insertProvider(req);
            if (CollectionUtils.isNotEmpty(req.getContactList())) {
                for (Contact contact : req.getContactList()) {
                    contact.setProviderId(req.getId());
                    contact.setCreateBy(SecurityUtils.getUsername());
                    contact.setCreateTime(new Date());
                }
                purProviderMapper.insertProviderContact(req.getContactList());
            }

        } else {
            //修改
            req.setUpdateBy(SecurityUtils.getUsername());
            req.setUpdateTime(new Date());
            purProviderMapper.updateProvider(req);
            //删除联系人
            purProviderMapper.deleteContactByProviderId(req.getId());
            if (CollectionUtils.isNotEmpty(req.getContactList())) {
                for (Contact contact : req.getContactList()) {
                    contact.setProviderId(req.getId());
                    contact.setCreateBy(SecurityUtils.getUsername());
                    contact.setCreateTime(new Date());
                }
                purProviderMapper.insertProviderContact(req.getContactList());
            }

        }
    }

    /**
     * 供应商列表查询
     *
     * @param req
     * @return
     */
    @Override
    public List<ProviderVo> selectProviderList(ProviderVo req) {
        return purProviderMapper.selectProviderList(req);
    }

    /**
     * 根据id查询供应商
     *
     * @param id
     * @return
     */
    @Override
    public ProviderAddReq getProviderById(Long id) {
        ProviderVo providerVo = new ProviderVo();
        providerVo.setId(id);
        List<ProviderVo> providerVoList = purProviderMapper.selectProviderList(providerVo);
        //处理有效期
        ProviderAddReq providerAddReq = new ProviderAddReq();
        BeanUtils.copyBeanProp(providerAddReq, providerVoList.get(0));
        return providerAddReq;
    }

    /**
     * 删除供应商
     *
     * @param id
     */
    @Override
    public void deleteProvider(Long id) {
        purProviderMapper.deleteProvider(id);
        purProviderMapper.deleteContactByProviderId(id);
    }

    /**
     * 提交申请
     *
     * @param vo
     */
    @Override
    public void startProviderProcess(ProviderVo vo) {
        //查询供应商信息
        ProviderAddReq provider = getProviderById(vo.getId());
        if (!vo.getStatus().equals(provider.getStatus())) {
            throw new CustomException("数据状态已更新，请刷新数据");
        }

        //流程定义的key
        String processDefinitionKey = "ProviderApprove";
        //业务key
        String businessKey = processDefinitionKey + ":" + vo.getId();

        Map<String, Object> variables = new HashMap<>();
        variables.put("username", SecurityUtils.getUsername());
        //启动流程
        runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, variables);
        //更新供应商审批状态
        ProviderAddReq providerAddReq = new ProviderAddReq();
        providerAddReq.setId(vo.getId());
        providerAddReq.setStatus("1");
        purProviderMapper.updateProvider(providerAddReq);
        //TODO 加入待办任务表


    }


    /**
     * 获取待办任务
     */
    @Override
    public List<TaskEntityResp> getProviderApproveList() {
        String assignee = SecurityUtils.getUsername();
        List<Task> list = taskService.createTaskQuery().taskAssignee(assignee).list();
        List<TaskEntityResp> returnList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(task -> {
                TaskEntityResp taskEntityResp = new TaskEntityResp();
                taskEntityResp.setId(task.getId());
                taskEntityResp.setName(task.getName());
                taskEntityResp.setCreateTime(task.getCreateTime());
                taskEntityResp.setAssignee(task.getAssignee());
                returnList.add(taskEntityResp);
            });
        }
        return returnList;
    }


    /**
     * 根据任务id查询供应商信息
     *
     * @param id
     */
    @Override
    public ProviderVo getProviderByTaskId(String id) {
        //根据任务id查询任务实例
        Task task = taskService.createTaskQuery().taskId(id).singleResult();
        //从任务实例中取出流程实例id
        String processInstanceId = task.getProcessInstanceId();
        //根据流程实例id获取流程实例对象
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        //获取businessKey
        String businessKey = processInstance.getBusinessKey();
        //获取id
        String businessId = businessKey.split(":")[1];
        //根据id查询供应商信息
        ProviderVo providerVo = new ProviderVo();
        providerVo.setId(Long.parseLong(businessId));
        List<ProviderVo> providerVos = purProviderMapper.selectProviderList(providerVo);
        ProviderVo vo = new ProviderVo();
        if (CollectionUtils.isNotEmpty(providerVos)) {
            vo = providerVos.get(0);
        }
        return vo;
    }

    /**
     * 生成供应商编号
     *
     * @return
     */
    private String getProviderNum() {
        //编号格式GYS-20200625001
        String providerNum = "GYS-";
        String newDateStr = DateUtils.dateTime();
        String maxProviderNum = purProviderMapper.getMaxProviderNum();
        if (StringUtils.isNotEmpty(maxProviderNum)) {
            String oldDateStr = maxProviderNum.substring(4, 12);
            if (newDateStr.equals(oldDateStr)) {
                String oldNum = maxProviderNum.substring(12);
                Integer newNum = Integer.parseInt(oldNum) + 1;
                providerNum = providerNum + newDateStr + (String.format("%03d", newNum));
            } else {
                providerNum = providerNum + newDateStr + "001";
            }

        } else {
            providerNum = providerNum + newDateStr + "001";
        }
        return providerNum;
    }
}
